import { ref, reactive } from 'vue';
import { ElNotification } from 'element-plus';
import { getQuery,updateReturn,updateShipReturn } from '@/axios/api/not_shipped/query';
import * as XLSX from 'xlsx';


export default function () {

    // 用户列表
    const tableData = ref([]);
    // 搜索框
    let con = ref('');
    let item = ref('');
    let caseno = ref('');

    // 当前页数
    let currentPage4 = ref(1);
    // 每页显示条数
    let pageSize4 = ref(20);
    // 总条数
    let total4 = ref(0);

    // 每页显示条目个数改变时触发
    const handler = () => {
        currentPage4.value = 1;
        handleSearch();
    }
    // 当前页数改变时触发
    const getHasUser = () => {
        handleSearch();
    }

    // 导出excel
    const exportExcel = async () => {
        let excelData = [];
        // 获取数据
        try {
            let res: any = await getQuery({
                con: con.value,
                item: item.value,
                caseno: caseno.value,
                currentPage4: currentPage4.value,
                pageSize4: pageSize4.value,
                flag: 1
            });
            excelData = res.data;
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
        if (excelData.length == 0) {
            ElNotification({
                title: 'Error',
                message: '没有数据',
                type: 'error',
            })
            return;
        }

        const ws = XLSX.utils.json_to_sheet(excelData); // 将数据转换为工作表
        const wb = { Sheets: { 'Data': ws }, SheetNames: ['Data'] }; // 创建工作簿
        const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); // 将工作簿转化为二进制缓冲区

        // 创建Blob对象并使用URL.createObjectURL方法生成URL
        const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
        const url = URL.createObjectURL(data);

        // 创建隐藏的可下载链接
        const link = document.createElement('a');
        link.href = url;
        link.style.display = 'none';
        link.download = 'data.xlsx'; // 设置下载文件名
        document.body.appendChild(link);

        // 触发点击下载
        link.click();
        // 清理
        setTimeout(() => {
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        }, 100);
    }

    // 获取用户列表
    const handleSearch = async () => {
        try {
            let res: any = await getQuery({
                con: con.value,
                item: item.value,
                caseno: caseno.value,
                currentPage4: currentPage4.value,
                pageSize4: pageSize4.value,
                flag: 0
            });
            tableData.value = res.data;
            total4.value = res.total || 0;
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }

    let restock_data = reactive({
        ID: '',
        ContractNo: '',
        Item: '',
        CaseNo: '',
        Qty: '',
        ReturnQty: '',
        yesqty: '',
        yes_qty: '',
    })
    // 抽屉
    let dialog = ref(false); // 是否显示抽屉
    let dialog1 = ref(false); // 是否显示抽屉

    // 抽屉表单校验

    const yes_qty = (_rule: any, value: any, callback: any) => {
        if (/^[1-9]\d*$/.test(value)==false) {
            callback(new Error('退库数量格式不正确,确保为正整数'))
        }
        else if (Number(value)>(Number(restock_data.Qty) - Number(restock_data.ReturnQty))) {
            callback(new Error('退库数量不能大于可退库数量:' + (Number(restock_data.Qty) - Number(restock_data.ReturnQty))))
        }
        else {
            callback()
        }
            
    };

    const rules = {
        yes_qty: [
            { validator: yes_qty, trigger: 'change' }
        ]
    }

    const handleRestock = async (row: any) => {
        if (row.ReturnQty == row.Qty) {
            ElNotification({
                title: 'Error',
                message: '该条数据已全部退库',
                type: 'error',
            })
            return;
        }
        restock_data.yes_qty = '';
        restock_data.ID = row.ID;
        restock_data.ContractNo = row.ContractNo;
        restock_data.Item = row.Item;
        restock_data.CaseNo = row.CaseNo;
        restock_data.Qty = row.Qty;
        restock_data.ReturnQty = row.ReturnQty;
        dialog.value = true;
    }

    
    // 处理退库

    const handleReturn = async () => {
        // 处理表单提交
        try {
            let res: any = await updateReturn({
                ID: restock_data.ID,
                yes_qty: restock_data.yes_qty,
            });
            if (res.code == 200) {
                ElNotification({
                    title: 'Success',
                    message: '退库成功',
                    type: 'success',
                })
                handleSearch();
                dialog.value = false;
            }else {
                ElNotification({
                    title: 'Error',
                    message: res.msg,
                    type: 'error',
                })
            }
            
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }

    }

    //发货
    let restock_data1 = reactive({
        ContractNo: '',
    })

    const handleRestock1 = async () => {

        restock_data1.ContractNo ='';
        dialog1.value = true;
    }

     // 抽屉表单校验

     const ContractNo = (_rule: any, value: any, callback: any) => {
        if (/^[A-Z0-9]{14}$/.test(value)) {
            callback() //通过
        } else if (value === '') {
            callback(new Error('请输入合同号'))
        } else {
            callback(new Error('合同号格式不正确,确保字符串长度正好为14位并且只包含大写字母和数字'))
        }
    };

    const rules1 = {
        ContractNo: [
            { validator: ContractNo, trigger: 'change' }
        ]
    }



    const handleShipReturn = async () => {
        try {
            let res: any = await updateShipReturn({
                ContractNo: restock_data1.ContractNo
            });
            if (res.code == 200) {
                ElNotification({
                    title: 'Success',
                    message: '发货成功',
                    type: 'success',
                })
                con.value = '';
                item.value = '';
                caseno.value = '';
                handleSearch();
                dialog1.value = false;
            }else {
                ElNotification({
                    title: 'Error',
                    message: res.msg,
                    type: 'error',
                })
            }
            
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }




    return {
        tableData,
        con,
        item,
        caseno,
        handleSearch,
        currentPage4,
        pageSize4,
        total4,
        handler,
        getHasUser,
        exportExcel,
        restock_data,
        dialog,
        rules,
        handleRestock,
        handleReturn,
        handleRestock1,
        dialog1,
        restock_data1,
        rules1,
        handleShipReturn
    }
}